package remoting;

import common.exception.RemotingException;
import common.factory.Factory;
import common.factory.MagicFactory;
import common.model.MagicUrl;
import remoting.channel.ChannelHandler;

public class Transporters {

  private Transporters() {
  }

  public static Server bind(String url, ChannelHandler... handler)
      throws RemotingException {
    return bind(MagicUrl.valueOf(url), handler);
  }

  public static Server bind(MagicUrl url, ChannelHandler... handlers)
      throws RemotingException {
    if (url == null) {
      throw new IllegalArgumentException("url == null");
    }
    if (handlers == null || handlers.length == 0) {
      throw new IllegalArgumentException("handlers == null");
    }
    ChannelHandler handler;
    if (handlers.length == 1) {
      handler = handlers[0];
    } else {
      handler = new ChannelHandlerDispatcher(handlers);
    }
    Server server = MagicFactory.getMagicFactory().getTransporter().bind(url, handler);
    return server;
  }

  public static Client connect(String url, ChannelHandler... handler)
      throws RemotingException {
    return connect(MagicUrl.valueOf(url), handler);
  }

  public static Client connect(MagicUrl url, ChannelHandler... handlers)
      throws RemotingException {
    if (url == null) {
      throw new IllegalArgumentException("url == null");
    }
    ChannelHandler handler;
    if (handlers == null || handlers.length == 0) {
      handler = new ChannelHandlerAdapter();
    } else if (handlers.length == 1) {
      handler = handlers[0];
    } else {
      handler = new ChannelHandlerDispatcher(handlers);
    }
    return MagicFactory.getMagicFactory().getTransporter().connect(url, handler);
  }

}
